'''


    Cycle Report views


'''
import json 

from django.http import HttpResponse
from django.template import Context, loader
from django.shortcuts import render_to_response, get_object_or_404

import TasK.models as models

THEMESWITCH = False # Show the theme switcher widget ?
CAN_EDIT = False # Show links to admin ?

def _print_exc(func):
    '''
    Decorator to print the stack on exception
    '''
    def wrapped(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except:
            import traceback
            traceback.print_exc()
            raise

    return wrapped


def index(req):
    '''
    
    '''
    cycles = models.Cycle.objects.all().order_by('-start_date')
    return render_to_response(
        'reports/cycles.html',
        {
            'cycles': cycles, 
            'THEMESWITCH':THEMESWITCH,
            'can_edit': req.GET.get('can_edit', CAN_EDIT),
        }
    )

def current(req):
    '''
    
    '''
    #return HttpResponse("Hello, world. You're in the CURRENT cycle report.")
    cycle = get_object_or_404(models.Cycle, status='CURRENT')
    return render_to_response('reports/cycles.html', {'cycles': [cycle]})

@_print_exc
def render_tasks(req, cycle_pk):
    cycle = get_object_or_404(models.Cycle, pk=cycle_pk)
    taches = cycle.taches.all()
    return render_to_response(
        'reports/tasks.html',
        {
            'cycle': cycle,
            'taches': taches, 
            'can_edit':req.GET.get('can_edit', CAN_EDIT),
        }
    )

@_print_exc
def render_summary(req, cycle_pk):
    cycle = get_object_or_404(models.Cycle, pk=cycle_pk)
    return render_to_response('reports/cycle_stats.html', {'cycle':  cycle}) 

@_print_exc
def get_fonctionalite_complete_list(req):
    term = req.GET.get('term', '')
    choices = [ f.name for f in models.Fonctionalite.objects.filter(name__icontains=term) ]
    choices = json.encoder.JSONEncoder().encode(choices)
    return HttpResponse(
        choices, mimetype="application/json"
    )

@_print_exc
def new_task_in_cycle(req):
    '''
    Create a task using the task name and fonctionalite name found in the
    request req.
    If the request contains a 'cycle_pk' value, the new task is added to the 
    cycle having this primary key.
    
    Possible return values:
        [0, ''] on success
        [1, 'Fonctionalite does not exists']
        [2, 'Task name is not valid']
        [3, 'Error finding cycle :(']
        [4, 'Error creating task']
    '''
    def response( code, message=''):
        ret = json.encoder.JSONEncoder().encode([code, message])
        return HttpResponse(
            ret, mimetype="application/json"
        )
        
    taskName = req.GET.get('tname', '').strip()
    fonctionaliteName = req.GET.get('fname', '').strip()
    description = req.GET.get('description', '')
    cycle_pk = req.GET.get('cycle_pk', '').strip()
    
    cycle = None
    if cycle_pk:
        try:
            cycle = get_object_or_404(models.Cycle, pk=cycle_pk)
        except:
            return response(3, "Error adding task to the given cycle :( (Cycle pk '"+cycle_pk+"' not found.")

    
    print 'new_task_in_cycle', (taskName, fonctionaliteName, description)
    
    if not taskName:
        return response(2, "Please give a name for the new task.")
    if not( 200 > len(taskName) > 3 ):
        return response(2, "The task name must be more than 3 and less than 200 character long.")
    
    if not fonctionaliteName:
        return response(1, "Please give a Fonctionalite name.")
    
    try:
        fonctionalite = get_object_or_404(models.Fonctionalite, name=fonctionaliteName)
    except:
        return response(1, "Fonctionalite '"+fonctionaliteName+"' does not exist.")

    try:
        models.Tache.create_in_cycle(
            name=taskName,
            fonctionalite=fonctionalite,
            description=description,
            cycle=cycle,
        )
    except Exception, err:
        import traceback
        traceback.print_exc()
        return response(4, "Error creatting the task: "+str(err))
    
    taches = cycle.taches.all()
    t = loader.get_template('reports/tasks.html')
    c = Context({
        'cycle_pk': cycle_pk,
        'taches': taches, 
        'can_edit':"False",
    })
    new_task_list = t.render(c)
    return response(0, new_task_list)

